package cn.j0n4than.accountingtool.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author jonathan
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置
     *
     * @param k       键
     * @param v       值
     * @param timeout 有效时间(ms)
     * @return boolean
     */
    public boolean set(String k, String v, long timeout) {
        try {
            this.redisTemplate.opsForValue().set(k, v, timeout, TimeUnit.MILLISECONDS);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 获取
     *
     * @param k 键
     * @return String
     */
    public String get(String k) {
        try {
            return this.redisTemplate.opsForValue().get(k);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 删除
     *
     * @param k 键
     * @return boolean
     */
    public boolean delete(String k) {
        try {
            return Boolean.TRUE.equals(this.redisTemplate.delete(k));
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }
}
